package net.midnighttd.engine.view;

import net.midnighttd.engine.map.Map;
import net.midnighttd.engine.view.sprite.Sprite;
import net.midnighttd.engine.Engine;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.*;

/**
 * Author: Adam Scarr
 * Date: 17/04/2009
 * Time: 7:19:30 PM
 *
 * A Component that combines the different layers of the game into a single component.
 */
public class EngineView extends JPanel implements MouseListener, MouseMotionListener {
    private LinkedList<Layer> layers = new LinkedList<Layer>();
    private Point mouse = new Point();
    private boolean mouseInFocus = false;
    protected Engine engine;
    

    public EngineView(Engine engine) {
        this.engine = engine;

        addMouseListener(this);
        addMouseMotionListener(this);

        setBorder(BorderFactory.createLineBorder(new Color(32, 29, 28)));

        reinit();
    }

    public void paintComponent(Graphics g) {
        g.setColor(new Color(191,187,184));
        g.fillRect(0,0,getWidth(),getHeight());
        for(Layer layer : layers) {
            layer.paintLayer(g);
        }

        engine.getSpriteManager().drawAll(g);

        draw(g);

        if(mouseInFocus) {
            drawMouse(g, mouse);
        }

        repaint();
    }

    protected void draw(Graphics g) {
        
    }

    protected void drawMouse(Graphics g, Point mouse) {
        
    }

    protected void mouseClicked(Point tile) {

    }

    public void mouseClicked(MouseEvent e) {}

    public void mousePressed(MouseEvent e) {
        Point p = new Point(e.getX(), e.getY());
        Point mapCoord = engine.getMapManager().getWorldLocation(p);
        mouseClicked(mapCoord);
    }

    public void mouseReleased(MouseEvent e) {}

    public void mouseEntered(MouseEvent e) {
        mouseInFocus = true;
    }

    public void mouseExited(MouseEvent e) {
        mouseInFocus = false;
    }

    public void mouseDragged(MouseEvent e) {
        mouse.x = e.getX();
        mouse.y = e.getY();
    }

    public void mouseMoved(MouseEvent e) {
        mouse.x = e.getX();
        mouse.y = e.getY();
    }

    public void reinit() {
        int width = 0;
        int height = 0;

        for(Map map: engine.getMapManager()) {
            Layer layer = new MapRenderer(map);
            layers.add(layer);

            if(layer.getHeight() > height) {
                height = layer.getHeight();
            }

            if(layer.getWidth() > width) {
                width = layer.getWidth();
            }
        }

        Dimension size = new Dimension(width, height);
        setMinimumSize(size);
        setPreferredSize(size);
    }
}
